package net.hvacapp.cmvrfforandroid.ui.mine;


import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.Fragment;
import android.util.Base64;

import com.mirror.android.common.util.ScreenUtils;

import net.hvacapp.cmvrfforandroid.R;
import net.hvacapp.cmvrfforandroid.adapter.BaseAdapterHelper;
import net.hvacapp.cmvrfforandroid.adapter.QuickAdapter;
import net.hvacapp.cmvrfforandroid.constant.Constant;
import net.hvacapp.cmvrfforandroid.http.BasicHttpClient;
import net.hvacapp.cmvrfforandroid.http.HttpCallbackHandle;
import net.hvacapp.cmvrfforandroid.http.HttpConstant;
import net.hvacapp.cmvrfforandroid.manager.AccountManager;
import net.hvacapp.cmvrfforandroid.model.GetUserProfileDataResp;
import net.hvacapp.cmvrfforandroid.model.UserProfileData;
import net.hvacapp.cmvrfforandroid.ui.EventBus.ProjectListRefreshEvent;
import net.hvacapp.cmvrfforandroid.ui.EventBus.UserListRefreshEvent;
import net.hvacapp.cmvrfforandroid.ui.fragment.BaseFragment;
import net.hvacapp.cmvrfforandroid.ui.listener.OnStateChangeListener;
import net.hvacapp.cmvrfforandroid.ui.project.model.ProjectInfoData;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.OnRefreshListener;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenu;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenuCreator;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenuItem;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenuLayout;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenuListView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.FragmentArg;
import org.androidannotations.annotations.ViewById;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * A simple {@link Fragment} subclass.
 */
@EFragment(R.layout.fragment_user_list)
public class UserListFragment extends BaseFragment implements OnStateChangeListener{

    @ViewById(R.id.lv_user)
    SwipeMenuListView mUserLv;
    @FragmentArg
    int typeValue;

    private int beginIndex = 0;
    private int endIndex = 0;

    private QuickAdapter<UserProfileData> mQuickAdapter;

    public UserListFragment() {
        // Required empty public constructor
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {

        }
    }

    @Override
    public void onStateChange() {
        if (this.isAdded()){

        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @AfterViews
    public void init(){
        EventBus.getDefault().register(this);

        if (mQuickAdapter == null){
            mQuickAdapter = new QuickAdapter<UserProfileData>(getActivity(),R.layout.two_lines_cell_item) {
                @Override
                protected void convert(BaseAdapterHelper helper, UserProfileData item) {
                    helper.setText(R.id.tv_title,item.getUserName())
                            .setText(R.id.tv_description,item.getName());
                }
            };
        }

        mUserLv.setAdapter(mQuickAdapter);

        // 设置左侧滑menu
        SwipeMenuCreator menuCreator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem menuItem = new SwipeMenuItem(getActivity());
                menuItem.setBackground(new ColorDrawable(Color.parseColor("#FFBA7F")));
                menuItem.setWidth((int) ScreenUtils.dpToPx(getActivity(), 80));
                menuItem.setTitleColor(getResources().getColor(R.color.cm_navigation_red_color));
                menuItem.setTitleSize(14);
                menu.addMenuItem(menuItem);
                if (typeValue == 0) {
                    menuItem.setTitle("认证用户");
                }
                else {
                    menuItem.setTitle("取消认证");
                }

            }
        };
        mUserLv.setMenuCreator(menuCreator);

        initData();

        initEvent();
    }


    private void initEvent() {

        mUserLv.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onPullDownRefresh() {
                // 下拉刷新
                beginIndex = 0;
                endIndex = Constant.PAGE_COUNT - 1;
                if (typeValue == 0) {
                    loadAllUserProfileData(beginIndex, endIndex, 0);
                } else {
                    loadAllUserProfileData(beginIndex, endIndex, 1);
                }
            }

            @Override
            public void onPullUpRefresh() {
                // 上拉加载
                beginIndex = mQuickAdapter.getCount();
                endIndex = beginIndex + Constant.PAGE_COUNT - 1;
                if (typeValue == 0) {
                    loadAllUserProfileData(beginIndex, endIndex, 0);
                } else {
                    loadAllUserProfileData(beginIndex, endIndex, 1);
                }
            }
        });

        mUserLv.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(SwipeMenuLayout swipeMenuLayout, int position, SwipeMenu menu, int index) {
                UserProfileData data = mQuickAdapter.getItem(position);
                if (typeValue == 0) {
                    modifyUserApproveData(1, data);
                } else {
                    modifyUserApproveData(0, data);
                }

                return true;
            }
        });

    }

    private void initData() {
        beginIndex = 0;
        endIndex = beginIndex + Constant.PAGE_COUNT - 1;
        if (typeValue == 0) {
            loadAllUserProfileData(beginIndex, endIndex, 0);
        } else {
            loadAllUserProfileData(beginIndex, endIndex, 1);
        }

    }


    private void loadAllUserProfileData(final int begin, int end, int approve) {
        Map<String, Object> param = new HashMap<>();

        param.put("si", begin);
        param.put("ei", end);
        param.put("Approved", approve);

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_ALL_CHILD_USERS_BY_TYPE, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetUserProfileDataResp>() {
            @Override
            public void onSuccess(GetUserProfileDataResp obj) {
                // 成功
                if (begin == 0) {
                    mQuickAdapter.clear();
                }
                mQuickAdapter.addAll(obj.getGetChildUserProfiles2Result());
                mUserLv.onRefreshComplete();
            }

            @Override
            public void onFailure(String response) {
                mUserLv.onRefreshComplete();
            }

        });

    }

    private void modifyUserApproveData(int isApproved, UserProfileData data) {
        Map<String, Object> param = new HashMap<>();

        param.put("Approved", isApproved);

        param.put("un", new String(Base64.encode((data.getUserName()).getBytes(), Base64.DEFAULT)));

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_APPROVE_USER, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetUserProfileDataResp>() {
            @Override
            public void onSuccess(GetUserProfileDataResp obj) {
                // 成功，刷新数据
                EventBus.getDefault().post(new UserListRefreshEvent());
            }

            @Override
            public void onFailure(String response) {
                showToast("设置用户认证数据失败");
            }

        });
    }

    /**
     * 处理通知
     *
     * @param event
     */
    public void onEvent(UserListRefreshEvent event) {
        beginIndex = 0;
        endIndex = Constant.PAGE_COUNT - 1;
        if (typeValue == 0) {
            loadAllUserProfileData(beginIndex, endIndex, 0);
        } else {
            loadAllUserProfileData(beginIndex, endIndex, 1);
        }
    }



}
